<template>
  <el-card class="top-card" :style="{minHeight: '800px'}" shadow="never">
    <el-row :gutter="16">
      <el-col :span="6">
        <el-col :span="16">
          <classify-select
            ref="classifySelect"
            :selectValue="warningId"
            @select="handleClassifySelect"
          />
        </el-col>
        <el-col :span="8">
          <div style="overflow: hidden">
            <el-button-group>
              <el-button size="mini" type="primary" @click="handleAdd" icon="el-icon-plus" />
              <el-button size="mini" type="primary" @click="handleMinus" icon="el-icon-minus" />
            </el-button-group>
          </div>
        </el-col>

        <el-col class="mt20">
          <ul class="mt20 ul" v-show="list.length > 0">
            <li
              :class="[ liIndex === item.ruleId ? 'liBg' : '', 'pl15']"
              v-for="(item,index) in list"
              :key="item.ruleId"
              @click="handleLiClick(item,index)"
            >
              <el-tooltip class="item" effect="dark" :content="item.ruleName" placement="top">
                <span class="span">{{ item.ruleName }}</span>
              </el-tooltip>
              <el-button
                class="fr mr10"
                @click.stop="handleBtnClick(item)"
                :type="item.repeal === 0 ? 'danger' : 'success'"
                size="mini"
              >{{ item.repeal === 0 ? '禁用' : '启用' }}</el-button>
            </li>
          </ul>
        </el-col>
      </el-col>
      <el-col class="parentCol" :span="18">
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="基本设置" name="first">
            <basic-set
              @repeatData="handleRepeatData"
              @notSubmit="handleNotSubmit"
              @basicData="handleBasicData"
              @gradeChange="handleGradeChange"
              ref="basicSet"
            />
          </el-tab-pane>
          <el-tab-pane label="预警通知设置" name="second">
            <notice-set
              @notSubmit="handleNotSubmit"
              @noticeData="handleNoticeData"
              ref="noticeSet"
            />
          </el-tab-pane>
          <el-tab-pane label="预警处置方式" name="third">
            <el-form :model="form" ref="form">
              <el-row>
                <el-col>
                  <el-form-item label="处置方式">
                    <el-radio-group size="small" v-model="form.disposalMode">
                      <el-radio-button :label="1">普通</el-radio-button>
                      <el-radio-button :label="2">考评</el-radio-button>
                      <el-radio-button :label="3">不处置</el-radio-button>
                    </el-radio-group>
                    <el-tooltip class="item" effect="dark" content="新增考评项" placement="top">
                      <el-button
                        v-show="form.disposalMode === 2"
                        type="primary"
                        class="fr"
                        icon="el-icon-plus"
                        @click="handleShowEval"
                      />
                    </el-tooltip>
                  </el-form-item>
                </el-col>
                <el-col v-show="form.disposalMode === 2">
                  <el-form-item>
                    <eval-table
                      :tableData="evalData"
                      @tableUpdate="handleEvalUpdate"
                      ref="evalTable"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <div class="tl-center">
          <el-button type="primary" @click="handleSubmit">{{ liIndex ? '修改' : '新增' }}</el-button>
        </div>
      </el-col>
    </el-row>
    <classify-modal ref="classifyModal" @refresh="handleRefresh" />
    <eval-transfer @chooseEval="handleChooseEval" ref="evalTransfer" />
  </el-card>
</template>

<script>
import { changeSelect, typeAll, typeDelete, warningRuleCreate, warningRuleAll, warningRuleQuery, warningRuleUpdate, ruleChangeState } from '@/api/prewarning'
import ClassifySelect from './ClassifySelect'
import ClassifyModal from './ClassifyModal'
import BasicSet from './BasicSet'
import NoticeSet from './NoticeSet'
import EvalTransfer from './EvalTransfer'
import EvalTable from './EvalTable'
import { openNotification } from '@/utils/util'

export default {
  components: {
    ClassifySelect,
    ClassifyModal,
    BasicSet,
    NoticeSet,
    EvalTransfer,
    EvalTable
  },
  data() {
    return {
      form: {
        disposalMode: null,
        evalItemId: null
      },
      warningId: null,
      name: null,
      activeName: 'first',
      typeData: [],
      basic: true,
      notice: true,
      list: [],
      liIndex: null,
      evalData: [],
      ruleId: null,
      param: {}
    }
  },
  mounted() {
    typeAll().then(res => {
      this.typeData = res.data
    })
    this.listAll()
  },
  methods: {
    handleRefresh() {
      this.$refs.classifySelect.getWarningTypeTree()
    },
    handleRepeatData(arr) {
      this.$refs.noticeSet.setRepeatData(arr)
    },
    listAll() {
      warningRuleAll().then(res => {
        this.list = res.data
      })
    },
    async handleBtnClick(item) {
      console.log('item', item)
      const id = item.ruleId
      const state = item.repeal === 0 ? 1 : 0
      const _this = this

      if (item.repeal === 0) {
        this.$confirm({
          title: '确认操作',
          content: `您确定禁用这条规则吗？`,
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          centered: true,
          async onOk() {
            // 调用删除接口，刷新表格数据
            const res = await ruleChangeState({ id, state })
            if (res.state === '000000') {
              openNotification('success', '禁用操作成功')
              _this.listAll()
            }
          }
        })
      } else {
        const res = await ruleChangeState({ id, state })
        if (res.state === '000000') {
          openNotification('success', '启用操作成功')
          this.listAll()
        }
      }
    },
    async handleLiClick(item) {
      this.liIndex = item.ruleId
      const res = await warningRuleQuery(item.ruleId)
      console.log('res', res)
      const {
        data: { warningRule, details, evalItem }
      } = res
      this.ruleId = warningRule.ruleId
      const { deptField, userField, thresholdValue } = warningRule
      this.$nextTick(() => {
        this.$set(this.form, 'disposalMode', warningRule.disposalMode)
        this.evalData = evalItem
      })

      this.$refs.basicSet.edit(warningRule, { thresholdValue })
      this.$refs.noticeSet.edit(details, { deptField, userField })
    },
    handleEvalUpdate(arr) {
      let arr1 = []
      arr.map(v => {
        arr1.push(v.evalItemId)
      })
      this.$set(this.param, 'ruleEval', arr1.join(','))
    },
    async handleClassifySelect(value) {
      this.warningId = value.id

      const res = await warningRuleAll({ warningId: value.id })
      if (res.state === '000000') {
        this.list = res.data
      }
    },
    handleNotSubmit(str) {
      this[`${str}`] = false
    },
    handleBasicData(obj) {
      this.basic = true
      console.log('obj', obj)
      this.$set(this.param, 'rule', { ...obj })
    },
    handleNoticeData(obj) {
      this.notice = true
      this.$set(this.param, 'notice', obj)
      // this.param = Object.assign(this.param, obj)
    },
    // 提交
    async handleSubmit() {
      // console.log('form', this.form)
      this.$refs.basicSet.postData()
      this.$refs.noticeSet.postData()
      if (this.form.disposalMode === 2) {
        this.handleEvalUpdate(this.evalData)
      }
      console.log('disposalMode', this.form.disposalMode)

      if (this.basic && this.notice) {
        if (this.form.disposalMode) {
          this.param.rule.disposalMode = this.form.disposalMode
          console.log('param', this.param)
          let res = '',
            mes = ''
          if (!this.liIndex) {
            // 新增
            res = await warningRuleCreate(this.param)
            mes = '新增操作成功'
          } else {
            // 修改
            res = await warningRuleUpdate({ ...this.param, ruleId: this.ruleId })
            mes = '修改操作成功'
          }
          if (res.state === '000000') {
            openNotification('success', mes)
            console.log('res', res)
            this.listAll()
            // 成功之后的清空操作
            this.$refs.basicSet.reset()
            this.$refs.noticeSet.reset()
            this.form = Object.assign({}, {})
            this.evalData = []
          }
        } else {
          this.$message.error('请选择处置方式')
        }
      } else {
        this.$message.error('请填写或选择页面上的必填项')
      }
    },
    handleTabClick() {
      console.log('name')
    },
    // 选择考评项之后，数组传递给基础设置的表格
    handleChooseEval(arr) {
      console.log('arr', arr)

      this.evalData = [...arr]
      // this.$refs.evalTable.chooseEval(arr)
      this.handleEvalUpdate(arr)
    },
    // 基础设置控制考评选择框显示
    handleShowEval() {
      this.$refs.evalTransfer.show(this.evalData)
    },
    // 监听基础设置里面的预警等级值的变化
    handleGradeChange(num) {
      this.$refs.noticeSet.gradeChange(num)
    },
    // 增加
    handleAdd() {
      this.$refs.classifyModal.edit(false, {})
    },
    // 减少
    handleMinus() {
      const _this = this
      this.$confirm({
        title: '删除操作',
        content: `您确定删除这条记录吗？`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        centered: true,
        async onOk() {
          // 调用删除接口，刷新表格数据
          const res = await typeDelete(_this.warningId)
          if (res.state === '000000') {
            openNotification('success', '删除成功')
            _this.$refs.classifySelect.getWarningTypeTree()
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.top-card {
  overflow: inherit;
}
.ul {
  border: 1px solid #ccc;
  padding-top: 10px;
}
.liBg {
  background-color: #1890ff;
  color: #ffffff;
}

.pl15 {
  padding: 10px 0 10px 15px;
  cursor: pointer;
  overflow: hidden;
}
.pl15:hover {
  background-color: #cccccc;
}

.span {
  float: left;
  margin-top: 4px;
  width: 60%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.parentCol >>> .el-tabs__content {
  overflow: inherit;
}
</style>